#include "head.h"


// 父子进程间通信的管道
int pipe_fd[2];

int main(void)
{

    if(pipe(pipe_fd) == -1)
        error(1, errno, "pipe");
    
    // 父进程
    if(fork() != 0)
        signal(SIGINT, handler);   

    // 子进程
    // 子进程脱离当前进程组
    setpgid(0, 0);
    
    // 创建+初始化线程池
    Pool_t* pool = create_pool();

    // 绑定端口，地址
    int fd = 0;
    tcp(&fd, IP, PORT);    

    // 增加监听
    int epoll_fd = epoll_create(1);
    epoll_add(epoll_fd, fd);
    epoll_add(epoll_fd, pipe_fd[0]);

    while(1)
    {
        struct epoll_event events[N];
        bzero(events, sizeof(events));
        printf("epoll_wait\n");
        int count = epoll_wait(epoll_fd, events, N, -1);

        printf("wait_count = %d\n", count);

        
        for(int i = 0; i < count; ++i)
        {
            int current_fd = events[i].data.fd;
            // 有新链接加入
            if(current_fd == fd)
            {
                int sock_fd = accept(fd, NULL, NULL);
                // epoll_add(epoll_fd, sock_fd);
                // 任务入队列， 唤醒线程
                awaken(pool, sock_fd);
            }
            // 管道可读，要结束了
            else if(current_fd == pipe_fd[0])
            {
                pthread_mutex_lock(&pool->mutex);
                pool->alive = false;
                
                int err = pthread_cond_broadcast(&pool->cond);
                if(err != 0)
                    error(1, err, "pthread_cond_broadcast");
                pthread_mutex_unlock(&pool->mutex);

                for(int i = 0; i < N; ++i)
                {
                    int err = pthread_join(pool->pthread_arr[i], NULL);
                    if(err != 0)
                        error(1, err, "pthread_join");
                }
                printf("进程号:%d 主线程%ld:已退出\n", getpid(), pthread_self());
                pthread_exit(NULL);
            }
        }
    }

    close(fd);
    free(pool);
    return 0;
}
